package com.china.zhuoyue.api.core

import com.alibaba.fastjson.JSON
import com.alibaba.fastjson.JSONObject
import com.china.zhuoyue.router.service.IUserService
import com.didi.drouter.api.DRouter
import okhttp3.FormBody
import okhttp3.Interceptor
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.RequestBody.Companion.toRequestBody
import okhttp3.Response
import okhttp3.ResponseBody.Companion.toResponseBody


class ConvertInterceptor : Interceptor {
    companion object {
        const val KEY_ERRNO = "errno"
        const val KEY_ERRMSG = "errmsg"

        const val KEY_CODE = "code"
        const val KEY_MSG = "msg"
        const val KEY_LIST = "list"
        const val KEY_DATA = "data"

        const val CONTENT_TYPE_KEY = "Api-Type"
        const val JSON_CONTENT_TYPE_VALUE = "JSON"
        const val JSON_CONTENT_TYPE_HEADER = "$CONTENT_TYPE_KEY:$JSON_CONTENT_TYPE_VALUE"
        const val JSON_CONTENT_TYPE = "Content-Type:application/json;charset=utf-8"
        const val PARAM = "PARAM"
        private val CONTENT_TYPE = "application/json;charset=utf-8".toMediaType()
    }

    private val mUserService: IUserService by lazy {
        DRouter.build(IUserService::class.java).getService()
    }

    override fun intercept(chain: Interceptor.Chain): Response {
        var request = chain.request()
        val contentType = request.header(CONTENT_TYPE_KEY)
        if (JSON_CONTENT_TYPE_VALUE == contentType && "POST" == request.method) {
            val formBody = request.body as? FormBody
            if (formBody != null) {
                try {
                    val params = JSONObject()
                    for (i in 0 until formBody.size) {
                        if (formBody.name(i) != PARAM)
                            params[formBody.name(i)] = formBody.value(i)
                    }
                    request = request.newBuilder()
                        .removeHeader(CONTENT_TYPE_KEY)
                        .apply {
                            mUserService.getToken().takeIf { it.isNotEmpty() }?.let {
                                header("ZY-Token", it)
                            }
                        }
                        .post(params.toJSONString().toRequestBody(CONTENT_TYPE))
                        .build()
                } catch (e: Throwable) {
                    throw InterceptorException("okhttp拦截器出异常")
                }
            }
        }
        val response = chain.proceed(request)
        var body = response.body?.string() ?: """{"msg":"ok","code":-1}""".trimIndent()
        // 物业这边接口需要处理一下
        if ((body.contains(KEY_ERRNO) || body.contains(KEY_ERRMSG))) {
            val dataJson = JSON.parseObject(body)
            dataJson[KEY_CODE] = dataJson[KEY_ERRNO]
            dataJson[KEY_MSG] = dataJson[KEY_ERRMSG]
            dataJson.remove(KEY_ERRNO)
            dataJson.remove(KEY_ERRMSG)
            if (dataJson.containsKey(KEY_LIST)) {
                dataJson[KEY_DATA] = dataJson[KEY_LIST]
                dataJson.remove(KEY_LIST)
            }
            body = dataJson.toJSONString()
        }
        return response.newBuilder().body(body.toResponseBody(CONTENT_TYPE)).build()
    }
}